import { defineStore } from 'pinia'
import { getMenuList, getUserInfo } from '@/services/mock'
import router from '@/router'
import useTagsViewStore from './tagsView'
import { generatorDynamicRouter } from '@/utils/generator-routers'

//格式化接口返回的菜单，不是菜单的不在左侧菜单展示
const formatMenu = (arr, list = []) => {
    arr.map((v) => {
        if (!v.isMenu) return
        let _obj = {
            label: v.title,
            key: v.name,
            iconName: v.iconName,
            path: v.path,
        }
        if (v.children && v.children.length) {
            let _list = formatMenu(v.children)
            _obj.children = _list
        }
        list.push(_obj)
    })
    return list
}

const useUserStore = defineStore('user', {
    state: () => ({
        userInfo: {}, //用户信息
        menuList: [], //菜单列表
        menuData: [],
        authList: ['click1', 'click2'], //按钮权限
    }),
    getters: {
        UserInfo() {
            return this.userInfo
        },

        MenuData() {
            return this.menuData
        },
    },
    actions: {
        //获取用户信息
        async getUserInfo() {
            let res = await getUserInfo()
            console.log(res)
            if (res.code === 200) {
                this.userInfo = res.data
                let res0 = await getMenuList()
                if (res0.code === 200) {
                    let menuList = formatMenu(res0.data)
                    this.menuData = res0.data
                    this.menuList = menuList
                    let _menuList = await generatorDynamicRouter(res0.data)
                    await _menuList.forEach((it) => {
                        router.addRoute(it)
                    })
                    return res0
                } else {
                    return res0
                }
            } else {
                return res
            }
        },

        //退出
        Logout() {
            const tagsViewStore = useTagsViewStore()

            const { fullPath } = router.currentRoute.value
            this.$patch({
                userInfo: {},
                menuList: [],
                menuData: [],
                authList: [],
            })
            tagsViewStore.clearView()

            localStorage.setItem('Token', null)
            //重定向到登录页
            router.replace({
                name: 'login',
                query: {
                    redirect: fullPath ? encodeURIComponent(fullPath) : '',
                },
            })
        },
    },
})

export default useUserStore
